package cn.kgc.springboot.common;

import cn.hutool.json.JSONUtil;
import cn.kgc.springboot.util.JWTUtil;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * @author: mosin
 * @version: v1.0  2022/8/5
 */
public class JWTHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取token  header
        String token = request.getHeader("token");
        // 验证token
        HashMap<String, Object> map = new HashMap<>();
        try {
            JWTUtil.checkToken(token);
            return true;
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            map.put("msg", "token过期");
            map.put("code", 110);
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            map.put("msg", "token签名错误");
            map.put("code", 120);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "token无效");
            map.put("code", 130);
        }

        //  map -> json 响应前端
        String s = JSONUtil.toJsonStr(map);
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(s);
        writer.close();

        return false;
    }
}
